package com.liser.southernstar.service;

import android.text.TextUtils;

import com.gprinter.command.EscCommand;
import com.gprinter.command.GpUtils;
import com.liser.print.bluetooth.BtManager;
import com.liser.print.bluetooth.callback.SendCallback;
import com.liser.print.bluetooth.helper.SubByteString;
import com.liser.southernstar.model.bean.GoodsPrintDetails;
import com.liser.southernstar.model.bean.GoodsPrintOverview;
import com.liser.southernstar.model.mapper.ConversionFactory;
import com.liser.southernstar.model.vo.GoodsGroupedItem;

import java.util.List;
import java.util.Vector;

import io.reactivex.Observable;

/**
 * 用户商品订单打印服务
 *
 * @author Administrator
 * @date 2020/1/13 9:30
 */
public class CustomerOrderPrintService {

    private static final String PRINT_LINE = "------------------------------------------------\n";

    public static final int PRINT_TOTAL_LENGTH = 48 * 3;
    public static final short PRINT_POSITION_0 = 0;
    public static final short PRINT_POSITION_1 = 26 * 3;
    public static final short PRINT_POSITION_2 = 32 * 3;
    public static final short PRINT_POSITION_3 = 42 * 3;
    public static final int MAX_GOODS_NAME_LENGTH = 22 * 3;

    public static final short PRINT_UNIT = 43;

    private static CustomerOrderPrintService customerOrderPrintService;

    public static CustomerOrderPrintService getInstance() {
        if (customerOrderPrintService == null) {
            return new CustomerOrderPrintService();
        }
        return customerOrderPrintService;
    }

    /**
     * 订单打印
     *
     * @param goodsGroupedItemList 商品信息
     * @return 回调
     */
    public Observable<String> orderPrinting(List<GoodsGroupedItem> goodsGroupedItemList, SendCallback sendCallback) {
        GoodsPrintOverview goodsPrintOverview = ConversionFactory.goodsPrintOverview(goodsGroupedItemList);
        Vector<Byte> byteVector = initCommand(goodsPrintOverview);
        byte[] data = GpUtils.ByteTo_byte(byteVector);
        return BtManager.getInstance().sendData(data);
    }

    private Vector<Byte> initCommand(GoodsPrintOverview goodsPrintOverview) {
        EscCommand esc = new EscCommand();
        // esc初始化
        esc.addInitializePrinter();

        // 商店名称
        shopName(esc, "贵州民族大学小李砂锅酸汤饭好吃又好喝味道念念不忘欢迎大家都来品尝");

        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);

        // 头部信息
        esc.addText("打印编号：" + goodsPrintOverview.getExpressSn());
        esc.addPrintAndLineFeed();
        esc.addText("操作时间：" + "2020-01-13 10:28");
        esc.addPrintAndLineFeed();
        esc.addText("操作员：" + "LISER");
        esc.addPrintAndLineFeed();

        esc.addText(PRINT_LINE);

        // 商品头信息
        esc.addSetHorAndVerMotionUnits((byte) PRINT_UNIT, (byte) 0);
        esc.addText("商品名");

        esc.addSetAbsolutePrintPosition(PRINT_POSITION_1);
        esc.addText("单价");

        esc.addSetAbsolutePrintPosition(PRINT_POSITION_2);
        esc.addText("数量");

        esc.addSetAbsolutePrintPosition(PRINT_POSITION_3);
        esc.addText("金额");

        esc.addPrintAndLineFeed();

        // 商品信息
        if (goodsPrintOverview.getGoodsList() != null && goodsPrintOverview.getGoodsList().size() > 0) {
            esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);
            List<GoodsPrintDetails> goodsPrintDetailsList = goodsPrintOverview.getGoodsList();
            for (int i = 0; i < goodsPrintDetailsList.size(); i++) {
                GoodsPrintDetails goodsPrintDetails = goodsPrintDetailsList.get(i);

                String[] goodsNames = SubByteString.getSubedStrings(goodsPrintDetails.getGoodsName(), 20);

                // 商品名称
                if (goodsNames != null && goodsNames.length > 0) {
                    esc.addText((i + 1) + "." + goodsNames[0]);
                } else {
                    esc.addText((i + 1) + "." + goodsPrintDetails.getGoodsName());
                }

                esc.addSetHorAndVerMotionUnits((byte) PRINT_UNIT, (byte) 0);

                // 单价
                short priceLength = (short) goodsPrintDetails.getGoodsPrice().length();
                short pricePosition = (short) (PRINT_POSITION_1 + 12 - priceLength * 3);
                esc.addSetAbsolutePrintPosition(pricePosition);
                esc.addText(goodsPrintDetails.getGoodsPrice());

                // 数量
                short numLength = (short) (goodsPrintDetails.getGoodsNum() + goodsPrintDetails.getGoodsUnit()).getBytes().length;
                short numPosition = (short) (PRINT_POSITION_2 + 14 - numLength * 3);
                esc.addSetAbsolutePrintPosition(numPosition);
                esc.addText(goodsPrintDetails.getGoodsNum() + goodsPrintDetails.getGoodsUnit());

                // 金额
                short amountLength = (short) goodsPrintDetails.getGoodsAmount().replace(" ", "").getBytes().length;
                short amountPosition = (short) (PRINT_POSITION_3 + 11 - amountLength * 3);
                esc.addSetAbsolutePrintPosition(amountPosition);
                esc.addText(goodsPrintDetails.getGoodsAmount());

                if (goodsNames == null || goodsNames.length == 0) {
                    esc.addPrintAndLineFeed();
                } else if (goodsNames.length > 1) {
                    for (int j = 1; j < goodsNames.length; j++) {
                        esc.addText(goodsNames[j]);
                        esc.addPrintAndLineFeed();
                    }
                }
            }

            esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);
            esc.addText(PRINT_LINE);
        }

        // 总计信息
        esc.addSelectJustification(EscCommand.JUSTIFICATION.RIGHT);// 设置打印居右

        if (!TextUtils.isEmpty(goodsPrintOverview.getSubsidy())) {
            esc.addText("优惠补贴：" + goodsPrintOverview.getSubsidy() + "元\n");
        }

        if (!TextUtils.isEmpty(goodsPrintOverview.getGoodsAmount())) {
            esc.addText("金额总计：" + goodsPrintOverview.getGoodsAmount() + "元\n");
        }

        if (!TextUtils.isEmpty(goodsPrintOverview.getOrderAmount())) {
            esc.addText("还需支付：" + goodsPrintOverview.getOrderAmount() + "元\n");
        }

        esc.addText(PRINT_LINE);

//        打印二维码
        if (!TextUtils.isEmpty(goodsPrintOverview.getQrCode())) {
            esc.addPrintAndLineFeed();
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);// 设置打印居中
            esc.addText("请打开微信，扫码付款\n");
            esc.addPrintAndLineFeed();
            // 48  49  50  51
            // 设置纠错等级
            esc.addSelectErrorCorrectionLevelForQRCode((byte) 0x31);
            // 设置qrcode模块大小
            esc.addSelectSizeOfModuleForQRCode((byte) 7);
            // 设置qrcode内容
            esc.addStoreQRCodeData(goodsPrintOverview.getQrCode());
            // 打印QRCode
            esc.addPrintQRCode();
            esc.addPrintAndLineFeed();
            esc.addText("请将二维码放平整后再扫码\n");
        }
        esc.addPrintAndFeedLines((byte) 3);

        // 加入查询打印机状态，打印完成后，此时会接收到GpCom.ACTION_DEVICE_STATUS广播
        esc.addQueryPrinterStatus();

        // 最终数据
        return esc.getCommand();
    }

    private void shopName(EscCommand esc, String shopName) {
        // 默认商店名称每行显示十个汉字
        String[] shopNames = SubByteString.getSubedStrings(shopName, 30);
        /* 设置打印居中 */
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
        /* 设置为倍高倍宽 */
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);

        if (shopNames != null) {
            for (String name : shopNames) {
                esc.addText(name + "Sample\n");
            }
        }
        // 与下层分隔1行
        esc.addPrintAndFeedLines((byte) 1);
    }
}